package com.molyfun.parents.activity.setting;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.account.LoginActivity;
import com.molyfun.parents.activity.common.BaseActivity;
import com.molyfun.parents.rest.BaseResponse;
import com.molyfun.parents.uievent.EventDispatcherEnum;
import com.molyfun.parents.utils.PreferencesStorageUtil;
import com.molyfun.parents.view.SinglineClearEditText;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MolificationAccountActivity extends BaseActivity implements View.OnClickListener {


    @InjectView(R.id.base_title_left)
    ImageView mBack;
    @InjectView(R.id.base_title)
    TextView mTitle;
    @InjectView(R.id.binding_accout)
    TextView mBindAccount;
    @InjectView(R.id.verification_account)
    SinglineClearEditText mVerificationAccount;
    @InjectView(R.id.get_verification_code)
    TextView mGetVerificationCode;
    @InjectView(R.id.confirm_button)
    TextView mConfirmutton;
    private MyCountDownTimer myCountDownTimer;
    @InjectView(R.id.new_account)
    SinglineClearEditText mNewAccount;


    public static void startActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, MolificationAccountActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_molification_account);
        ButterKnife.inject(this);
        initData();

    }

    private void initData() {
        getSupportActionBar().setTitle("");
        mTitle.setText("更换账户");
        mNewAccount.setHint("请输入您要更换的手机号码");
        mVerificationAccount.setHint("请输入短信验证码");
        mBindAccount.setText(PreferencesStorageUtil.getPhoneNum(this));

        mBack.setOnClickListener(this);
        mGetVerificationCode.setOnClickListener(this);
        mConfirmutton.setOnClickListener(this);
        myCountDownTimer = new MyCountDownTimer(60000, 1000);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.base_title_left:
                finish();
                break;
            case R.id.get_verification_code:
                String phone = mNewAccount.getString();
                if (!TextUtils.isEmpty(phone) && !phone.equals(PreferencesStorageUtil.getPhoneNum(this))) {
                    if (isMobileNO(phone)) {
                        getVerificationCode(phone);
                    } else {
                        toast("电话号码有误");
                    }
                } else {
                    if (TextUtils.isEmpty(phone)) {
                        toast("电话号码不能为空");
                    } else {
                        toast("此号码已注册过");
                    }
                }

                break;
            case R.id.confirm_button:
                String phoneSubmit = mNewAccount.getString();
                String captche = mVerificationAccount.getString();
                if (!TextUtils.isEmpty(phoneSubmit) && !TextUtils.isEmpty(captche)) {
                    if (isMobileNO(phoneSubmit)) {
                        submitCaptche(phoneSubmit, captche);
                    } else {
                        toast("电话号码有误");
                    }
                } else {
                    toast("电话号码或验证码不能为空");
                }
                break;
        }
    }

    private void submitCaptche(String phone, String captcheCode) {
        showProgressDialog();
        Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().submitCaptcheInfo(phone, captcheCode);
        call.enqueue(new Callback<BaseResponse>() {
            @Override
            public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                dismissProgressDialog();
                if (response.body() != null) {
                    if(response.body().getCode() == 200){
                        LoginActivity.startActivity(MolificationAccountActivity.this);
                        finish();
                        Message uimessage = new Message();
                        uimessage.what = EventDispatcherEnum.UI_EVENT_SETTING_MOLIFICATION_ACCOUNT;
                        MFPApplication.getInstance().getEventDispatcher().sendMessage(uimessage);
                    }else{
                        toast(response.body().getMsg());
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseResponse> call, Throwable t) {
                dismissProgressDialog();
                toast("提交信息失败");
            }
        });
    }

    private void getVerificationCode(String phone) {
        showProgressDialog();
        Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().getCaptche(phone);
        call.enqueue(new Callback<BaseResponse>() {
            @Override
            public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                dismissProgressDialog();
                if (response.body() != null) {
                    if (response.body().getCode() == 200 && response.body().getMsg() != null) {
                        myCountDownTimer.start();
                        mConfirmutton.setClickable(true);
                        toast("验证码已发送，请注意查收");
                    } else if (response.body().getCode() == 300 && response.body().getMsg() != null) {
                        toast(response.body().getMsg());
                    } else {
                        toast("验证码获取异常");
                    }
                }

            }

            @Override
            public void onFailure(Call<BaseResponse> call, Throwable t) {
                dismissProgressDialog();
                toast("验证码获取失败");
            }
        });
    }

    private class MyCountDownTimer extends CountDownTimer {



        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        //计时过程
        @Override
        public void onTick(long l) {
            //防止计时过程中重复点击
            mGetVerificationCode.setClickable(false);
            mGetVerificationCode.setText(l / 1000 + "s");
        }

        //计时完毕的方法
        @Override
        public void onFinish() {
            //重新给Button设置文字
            mGetVerificationCode.setText("重新获取验证码");
            //设置可点击
            mGetVerificationCode.setClickable(true);
        }

    }

    public static boolean isMobileNO(String mobiles) {
// Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");//已过时
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(17[0-9])|(18[0-9]))\\d{8}$");//新加所有18段 17段
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }
}
